﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zor_Modes;
using Zor_IDAL;
using Zor_Tools;

namespace Zor_DAL
{
    public class Sys_Roles_DAL<T> where T : class
    {
        /// <summary>
        /// 角色管理-修改
        /// </summary>
        /// <param name="roles">角色对象</param>
        /// <returns>执行结果：1 成功 0失败</returns>
        public static BaseAnswer UpdateRoles(Sys_Roles roles)
        {
            var sql = "";
            if(roles.Role_Name != null)
                sql +="if not exists(select Role_Name from [Sys_Roles] where Role_Name =@Role_Name ) ";

            sql += "update [Sys_Roles] set Role_Name=@Role_Name  where Roles_Id = @Roles_Id";

            BaseAnswer bar = DapperEdit<T>.DoEdit(sql, new { Role_Name = roles.Role_Name, Roles_Id = roles.Roles_Id });
            return bar;
        }


        /// <summary>
        /// 角色管理-新增
        /// </summary>
        /// <param name="roles">角色对象</param>
        /// <returns>执行结果：1 成功 0失败</returns>
        public static BaseAnswer InsertRoles(Sys_Roles roles)
        {
            var sql = @"if not exists(select Role_Name from [Sys_Roles] where Role_Name =@Role_Name ) 
                        insert into Sys_Roles values 
                        (@Role_Name,@Role_CreateDate,@Role_CreateName)";

            BaseAnswer bar = DapperInsert<T>.DoInsert(sql, new 
            { 

                Role_Name = roles.Role_Name, 
                Role_CreateDate = TimeHelper.ToTimeStamp(DateTime.Now), 
                Role_CreateName = RequestSession.GetSessionUser().User_Id


            });
            return bar;
        }


        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">Id集合</param>
        /// <returns></returns>
        public static BaseAnswer DeleteRoles(int[] id)
        {
            var sql = @"if not exists(select count(0) from Sys_Users where Roles_Id = Roles_Id) 
                            delete from [Sys_Roles]  where  Roles_Id in @Roles_Id";
            BaseAnswer bar = DapperDelete<T>.DoDelete(sql, new { Roles_Id = id.ToArray<int>()});
            return bar;
        }


        /// <summary>
        /// 权限分配
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="menuId">权限菜单ID</param>
        /// <returns></returns>
        public static BaseAnswer Allocation(string roleId, string[] menuId)
        {

            List<string> lstsql = new List<string>();
            lstsql.Add("delete from [Sys_Jurisdiction] where Roles_Id=" + roleId + "");

            menuId.ToList<string>().ForEach(c =>
            {
                lstsql.Add("insert into dbo.Sys_Jurisdiction values(" + c + "," + roleId + "," + TimeHelper.ToNowTimeStamp() + "," + RequestSession.GetSessionUser().User_Id + ");");
            });
            BaseAnswer bar = DapperTransaction.DoTransaction(lstsql);
            return bar;
        }
    }
}
